package service

import (
	"context"
	"encoding/json"
	"fmt"
	"goods-server/basic/inits"
	__ "goods-server/basic/proto"
	"goods-server/handler/models"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedGoodsServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) AddGoods(_ context.Context, in *__.AddGoodsReq) (*__.AddGoodsResp, error) {
	goods := models.Goods{
		GoodsName:  in.GoodsName,
		GoodsPrice: uint(in.GoodsPrice),
		GoodsDesc:  in.GoodsDesc,
		GoodsImg:   in.GoodsImg,
	}
	if err := goods.CreateGoods(); err != nil {
		return nil, fmt.Errorf("商品发布失败")
	}
	return &__.AddGoodsResp{
		Id: int64(goods.Id),
	}, nil
}

// 分页展示
func (s *Server) GoodsList(_ context.Context, in *__.GoodsListReq) (*__.GoodsListResp, error) {
	var goodsLists []*__.GoodList
	var g models.Goods
	g.Id = uint(in.Id)
	list, err := g.GetGoodsList(int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, fmt.Errorf("商品列表分页展示失败")
	}
	for _, goods := range list {
		goodsLists = append(goodsLists, &__.GoodList{
			GoodsName:  goods.GoodsName,
			GoodsImg:   goods.GoodsImg,
			GoodsPrice: int64(goods.GoodsPrice),
			GoodsDesc:  goods.GoodsDesc,
			Id:         int64(goods.Id),
		})
	}
	return &__.GoodsListResp{
		List: goodsLists,
	}, nil
}

// 商品详情
func (s *Server) GoodsDetail(_ context.Context, in *__.GoodsDetailReq) (*__.GoodsDetailResp, error) {
	var goodsLists []*__.GoodList
	var g models.Goods
	g.Id = uint(in.Id)
	get := inits.ReidsDB.Get(inits.Ctx, "goodsDetail").Val()
	if get == "" {
		if err := g.GetGoodsDetail(); err != nil {
			return nil, fmt.Errorf("商品详情展示失败")
		}
		marshal, _ := json.Marshal(&goodsLists)
		inits.ReidsDB.Set(inits.Ctx, "goodsDetail", marshal, time.Minute*60)
		fmt.Println("数据库中获取数据")
	} else {
		json.Unmarshal([]byte(get), &goodsLists)
		fmt.Println("缓存中获取数据")
	}

	return &__.GoodsDetailResp{
		Id:         int64(g.Id),
		GoodsName:  g.GoodsName,
		GoodsImg:   g.GoodsImg,
		GoodsPrice: int64(g.GoodsPrice),
		GoodsDesc:  g.GoodsDesc,
	}, nil
}

// 用户登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	user := models.User{
		Username: in.Username,
		Password: in.Password,
	}
	if err := user.GetUserByUsername(); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("该用户不存在，禁止登录")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	return &__.LoginResp{
		Id: int64(user.Id),
	}, nil
}
